package com.yzjs.common.util;

import com.yzjs.common.exception.RRException;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class FileUtil {

//	public static void main(String[] args) {
//		//String dirName = "d:/FH/topic/";// 创建目录
//		File file = new File("D:/software/project/OAZN/main/java/com/yuqm/entity/merc/MercEntity.java");
//		FileUtil.createFile(file);
//	}



	public static void removeTempFile(String path) {
		File file = new File(path);
		file.delete();
	}

	public static void deleteDir(File dir) {
		if (dir.isDirectory()) {
			String[] children = dir.list();
			for (int i = 0; i < children.length; i++)
				deleteDir(new File(dir, children[i]));
		}
		dir.delete();
	}

	public static void download(HttpServletResponse response, String path) {
		File file = new File(path);
		if (!file.exists()) {
			response.addHeader("Content-Type", "application/json;charset=utf-8");
			throw new RRException("文件不存在");
		}
		try {
			download(response, new FileInputStream(path), file.getName());
		} catch (Exception ex) {
			throw new RRException("文件下载失败");
		}
	}

	public static void download(HttpServletResponse response, InputStream fis, String fileName) {
		OutputStream toClient = null;
		try {
			response.setHeader("Access-Control-Allow-Origin", "*");
			response.setCharacterEncoding("UTF-8");
			if (fis == null) {
				response.addHeader("Content-Type", "application/json;charset=utf-8");
				throw new RRException("文件不存在");
			}
			response.addHeader("Content-Type", "application/octet-stream;charset=utf-8");
			response.addHeader("Content-Disposition", "attachment; filename=" + new String(fileName
					.getBytes("UTF-8"), "ISO-8859-1"));
			fis = new BufferedInputStream(fis);
			toClient = new BufferedOutputStream((OutputStream)response.getOutputStream());
			byte[] buffer = new byte[4096];
			int length = -1;
			while ((length = fis.read(buffer)) != -1) {
				toClient.write(buffer, 0, length);
				toClient.flush();
			}
		} catch (IOException ex) {
			throw new RRException("文件导出失败");
		} finally {
			try {
				if (fis != null)
					fis.close();
				if (toClient != null)
					toClient.close();
			} catch (Exception exception) {}
		}
	}

	public static void toZip(File sourceFile, OutputStream out, boolean isDeleteOnSuccess) {
		ZipOutputStream zos = null;
		try {
			zos = new ZipOutputStream(out);
			compress(sourceFile, zos, sourceFile.getName());
			if (isDeleteOnSuccess) {
				org.apache.commons.io.FileUtils.deleteQuietly(sourceFile);
			}
		} catch (Exception e) {
			throw new RRException("文件不存在");
		} finally {
			if (zos != null)
				try {
					zos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
	}

	public static void toZip(List<File> srcFiles, OutputStream out, boolean isDeleteOnSuccess) {
		ZipOutputStream zos = null;
		try {
			zos = new ZipOutputStream(out);
			for (File srcFile : srcFiles)
				compressFile(srcFile, zos, srcFile.getName());
			if (isDeleteOnSuccess)
				for (File srcFile : srcFiles)
					org.apache.commons.io.FileUtils.deleteQuietly(srcFile);
		} catch (Exception e) {
			throw new RuntimeException("zip error from ZipUtils", e);
		} finally {
			if (zos != null)
				try {
					zos.close();
				} catch (IOException iOException) {}
		}
	}

	private static void compress(File sourceFile, ZipOutputStream zos, String name) throws IOException {
		if (sourceFile.isFile()) {
			compressFile(sourceFile, zos, name);
		} else {
			File[] listFiles = sourceFile.listFiles();
			if (listFiles == null || listFiles.length == 0) {
				zos.putNextEntry(new ZipEntry(name + "/"));
				zos.closeEntry();
			} else {
				for (File file : listFiles)
					compress(file, zos, name + "/" + file.getName());
			}
		}
	}

	private static void compressFile(File sourceFile, ZipOutputStream zos, String name) throws IOException {
		FileInputStream in = null;
		try {
			byte[] buf = new byte[4096];
			if (sourceFile.isFile()) {
				zos.putNextEntry(new ZipEntry(name));
				int len = 0;
				in = new FileInputStream(sourceFile);
				while ((len = in.read(buf)) != -1)
					zos.write(buf, 0, len);
				zos.closeEntry();
				in.close();
			}
		} finally {
			if (in != null)
				in.close();
		}
	}


	/**
	 * 创建文件顺便创建父目录
	 *
	 * @param file file类
	 */
	private static void createFile(File file) {
		if (file.exists() && file.isFile()) {
			file.delete();
			try {
				file.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return;
		}
		File parentFile = file.getParentFile();
		if (parentFile.exists()) {
			if (parentFile.isFile()) {
				parentFile.delete();
				parentFile.mkdirs();
			}
		} else {
			parentFile.mkdirs();
		}
		try {
			file.createNewFile();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 删除文件
	 * 
	 * @param filePathAndName
	 *            String 文件路径及名称 如c:/fqf.txt
	 * @param
	 *
	 * @return boolean
	 */
	public static void delFile(String filePathAndName) {
		try {
			String filePath = filePathAndName;
			filePath = filePath.toString();
			File myDelFile = new File(filePath);
			myDelFile.delete();

		} catch (Exception e) {
			System.out.println("删除文件操作出错");
			e.printStackTrace();

		}

	}

	/**
	 * 读取到字节数组0
	 * 
	 * @param filePath //路径
	 * @throws IOException
	 */
	public static byte[] getContent(String filePath) throws IOException {
		File file = new File(filePath);
		long fileSize = file.length();
		if (fileSize > Integer.MAX_VALUE) {
			System.out.println("file too big...");
			return null;
		}
		FileInputStream fi = new FileInputStream(file);
		byte[] buffer = new byte[(int) fileSize];
		int offset = 0;
		int numRead = 0;
		while (offset < buffer.length
				&& (numRead = fi.read(buffer, offset, buffer.length - offset)) >= 0) {
			offset += numRead;
		}
		// 确保所有数据均被读取
		if (offset != buffer.length) {
			throw new IOException("Could not completely read file "
					+ file.getName());
		}
		fi.close();
		return buffer;
	}

	/**
	 * 读取到字节数组1
	 * 
	 * @param filePath
	 * @return
	 * @throws IOException
	 */
	public static byte[] toByteArray(String filePath) throws IOException {

		File f = new File(filePath);
		if (!f.exists()) {
			throw new FileNotFoundException(filePath);
		}
		ByteArrayOutputStream bos = new ByteArrayOutputStream((int) f.length());
		BufferedInputStream in = null;
		try {
			in = new BufferedInputStream(new FileInputStream(f));
			int buf_size = 1024;
			byte[] buffer = new byte[buf_size];
			int len = 0;
			while (-1 != (len = in.read(buffer, 0, buf_size))) {
				bos.write(buffer, 0, len);
			}
			return bos.toByteArray();
		} catch (IOException e) {
			e.printStackTrace();
			throw e;
		} finally {
			try {
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			bos.close();
		}
	}

	/**
	 * 读取到字节数组2
	 * 
	 * @param filePath
	 * @return
	 * @throws IOException
	 */
	public static byte[] toByteArray2(String filePath) throws IOException {

		File f = new File(filePath);
		if (!f.exists()) {
			throw new FileNotFoundException(filePath);
		}

		FileChannel channel = null;
		FileInputStream fs = null;
		try {
			fs = new FileInputStream(f);
			channel = fs.getChannel();
			ByteBuffer byteBuffer = ByteBuffer.allocate((int) channel.size());
			while ((channel.read(byteBuffer)) > 0) {
				// do nothing
				// System.out.println("reading");
			}
			return byteBuffer.array();
		} catch (IOException e) {
			e.printStackTrace();
			throw e;
		} finally {
			try {
				channel.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				fs.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * Mapped File way MappedByteBuffer 可以在处理大文件时，提升性能
	 * 
	 * @param filePath
	 * @return
	 * @throws IOException
	 */
	public static byte[] toByteArray3(String filePath) throws IOException {

		FileChannel fc = null;
		RandomAccessFile rf = null;
		try {
			rf = new RandomAccessFile(filePath, "r");
			fc = rf.getChannel();
			MappedByteBuffer byteBuffer = fc.map(MapMode.READ_ONLY, 0,
					fc.size()).load();
			//System.out.println(byteBuffer.isLoaded());
			byte[] result = new byte[(int) fc.size()];
			if (byteBuffer.remaining() > 0) {
				// System.out.println("remain");
				byteBuffer.get(result, 0, byteBuffer.remaining());
			}
			return result;
		} catch (IOException e) {
			e.printStackTrace();
			throw e;
		} finally {
			try {
				rf.close();
				fc.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}


	/**
	 * @description 写文件
	 * @param
	 * @throws UnsupportedEncodingException
	 * @throws IOException
	 */
	public static boolean writeTxtFile(String content, File fileName, String encoding) {
		FileOutputStream o = null;
		boolean result=false;
		try {

			//文件以及文件夹存在 新建文件
			createFile(fileName);
			o = new FileOutputStream(fileName);
			o.write(content.getBytes(encoding));
			result=true;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (o != null) {
				try {
					o.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		return result;
	}

}